<?php
/**
 * Created by PhpStorm.
 * User: Jacob Shi
 * Date: 2016/6/16
 * Time: 16:12
 */

class Silk_Mapi_Model_Observer_Gift
{
    private $_context = null;

    public function setContext($context)
    {
        $this->_context = $context;
    }

    public function getContext()
    {
        return $this->_context;
    }

    private function _initProduct($id)
    {
        if(is_object($id) && ($id instanceof Mage_Catalog_Model_Product))
        {
            return $id;
        }
        $product = Mage::getModel("catalog/product")
            ->setStoreId(Mage::app()->getStore()->getId())
            ->load($id);
        if($product && $product->getId())
        {
            return $product;
        }
        else
        {
            throw new Exception("商品不存在！");
        }
    }

    /**
     * Get request for product add to cart procedure
     *
     * @param   mixed $requestInfo
     * @return  Varien_Object
     */
    protected function _initProductRequest($requestInfo)
    {
        if ($requestInfo instanceof Varien_Object) {
            $request = $requestInfo;
        } elseif (is_numeric($requestInfo)) {
            $request = new Varien_Object(array('qty' => $requestInfo));
        } else {
            $request = new Varien_Object($requestInfo);
        }

        if (!$request->hasQty()) {
            $request->setQty(1);
        }

        return $request;
    }

    public function getGiftsByProduct($product)
    {
        $gifts = Mage::getModel('pms/gift')->getCollection()
            ->addFieldToFilter('product_id', array('eq'=>$product->getId()))
            ->addValidateFilter();
        return $gifts;
    }


    public function addProduct($id)
    {
        $this->log("Match", $id);
        $product = $this->_initProduct($id);
        $context = $this->getContext();
        if(!$product) return;

        $this->log("Check Gift", $id);
        $gifts = $this->getGiftsByProduct($product);

        if(!$gifts->count()) return;
        $this->log("Has Gift", $id);
        $quote = $this->getContext()->getQuote();

        $item = $quote->getItemByProduct($product);

        $giftItem = array();

        foreach($gifts as $gift)
        {
            $giftProduct = $this->_initProduct($gift->getGiftProductId());
            if(!$giftProduct->isInStock()) continue;
            //if($item->getQty()<$gift->getDiscountStep()) continue;
            $limit = $gift->getCustomerLimit();
//            $totals = Mage::getModel('sales/quote_item')
//                ->getCollection()
//                ->addCustomerFilter($context->getApiUser()->getUserId())->count();
            $db = Mage::getSingleton("core/resource")->getConnection('core_read');
            $customerId = $context->getApiUser()->getUserId();
            $giftId = $gift->getId();
            $sql = "select sum(qty_ordered) from sales_flat_order_item i left join sales_flat_order q on i.order_id=q.entity_id where i.gift_id='{$giftId}' and q.customer_id='{$customerId}' and q.state!='canceled'";
            $query = $db->query($sql);
            $usedQty = $query->fetchColumn();
            if($usedQty>$limit)
            {
                continue;
            }

            $maxQty = $limit - $usedQty;
            $this->log("Max Qty:{$maxQty}", $id);

            $freeGift = floor($item->getQty()/$gift->getDiscountStep())*$gift->getDiscountQty();
            $this->log("freeGiftQty1:".$freeGift);
            
            if(($freeGift+$gift->getUsedQty())>$gift->getGiftQty())
            {
                $freeGift = $gift->getGiftQty()-$gift->getUsedQty();
            }

            if($freeGift>$maxQty) $freeGift = $maxQty;

            $this->log("freeGiftQty2:".$freeGift);
            $giftItem = Mage::getModel('sales/quote_item')->getCollection()->setQuote($quote)
                ->addFieldToFilter('parent_item_id', array('eq'=>$item->getId()))
                ->addFieldToFilter('product_id', array('eq'=>$gift->getGiftProductId()))
                ->addFieldToFilter('gift_id', array('eq'=>$gift->getId()))->getFirstItem();
            $this->log("freeGiftQty3:".$freeGift);
            if($giftItem && $giftItem->getId())
            {
                if($freeGift) {
                    $this->log("has a free gift");
                    $giftItem->setQty($freeGift);
                    $giftItem->setCustomPrice(0);
                    $giftItem->save();

                }
                else
                {
                    $giftItem->delete();
                }
            }
            else
            {
                if(!$freeGift) continue;
                $this->log("freeGiftQty4:".$freeGift);

                $info = $this->_initProductRequest($freeGift);
                //throw new Exception($giftProduct->getId());
                Mage::unregister("gift_product_id");
                Mage::unregister("gift_id");
                Mage::register("gift_product_id",$giftProduct->getId());
                Mage::register("gift_id",$gift->getId());
                $giftItem = $quote->addProduct($giftProduct, $info);
                //$giftItem->setGiftId($gift->getId());
                //$giftItem->setCustomPrice(0);
                $giftItem->save();
                //$quote->setTotalsCollectedFlag(false);
                $quote->save();
                //throw new Exception(1);
                //$quote = $this->getContext()->getQuote(true);
                Mage::unregister("gift_product_id");
                Mage::unregister("gift_id");
                //$this->log(get_class($giftItem));
                //$this->log("giftItem:".$giftItem->getId());
                //$giftItem = $quote->getItemById($giftItem->getId());
                if($giftItem && $giftItem->getId())
                {
                    $giftItem->setParentItemId($item->getId());
                    //$giftItem->setGiftId($gift->getId());
                    //$giftItem->setCustomPrice(0);
                    $giftItem->save();
                    //$quote->setTotalsCollectedFlag(false);
                    $quote->collectTotals()->save();

                }
            }
        }
    }

    //remove invalidate gift before order
    public function validateGift()
    {

        $context = $this->getContext();
        $quote = $this->getContext()->getQuote();

        $items = $quote->getAllItems();

        foreach($items as $item)
        {
            $giftId = $item->getGiftId();
            if($giftId) continue;

            $this->addProduct($item->getProductId());
        }

        //$quote->collectTotals()->save();
        $changed = false;
        foreach($items as $item)
        {
            $giftId = $item->getGiftId();
            if($giftId)
            {
                $gift = Mage::getModel("pms/gift")->load($giftId);
                if(!$gift->isValidate())
                {
                    $changed = true;
                    //$item->delete();
                }
            }
        }
        //if($changed) $quote->collectTotals()->save();
        $quote->collectTotals()->save();
    }

    public function updateProduct($id)
    {

    }

    public function deleteProduct($id)
    {

    }

    public function log($msg,$id=0)
    {
        Mage::log($id." : ".$msg,null,"gift.log");
    }
}